package com.live.proxy.tool;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.live.proxy.R;
import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.view.ToastBottomUtils;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class UpdateChecker {
    private Activity mActivity;
    private boolean isTishi;
    //
    public UpdateChecker(Activity activity, boolean tishi) {
        mActivity = activity;
        isTishi = tishi;
    }
    //1.检查是否是最新版本
    public void checkForUpdates() {
        try {
            UserDatabase userDb= new UserDatabase(mActivity);
            UserModel userModel = userDb.select();
            getAccount(GetUtil.ProxyAppinfo(),GetUtil.getAppInfo(mActivity).toString(),userModel.getToken());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastBottomUtils.Setinfo(mActivity,msg.obj.toString());
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        int code = json.getInt("code");
                        switch (code){
                            case 200://成功
                                JSONObject valueJson = json.getJSONObject("data");
                                String updateMessage = valueJson.getString("version_message");
                                String apkUrl = valueJson.getString("version_url");
                                int apkCode = Integer.valueOf(valueJson.getString("version_code"));
                                int versionCode = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionCode;
                                if (apkCode > versionCode) {
                                    showUpdateDialog(apkUrl,updateMessage);
                                }
                                break;
                            default:
                                //201  没有传值；202  账户或密码错误；203  查询数据为空
                                if(isTishi) {
                                    ToastBottomUtils.Setinfo(mActivity,json.getString("info"));
                                }
                                break;
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 得到服务器返回的具体内容
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
            @Override
            public void onFailure(Call call, IOException e) {
                // 在这里对异常情况进行处理
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "获取版本号异常，请联系管理员";
                handler.sendMessage(message);
            }

        },token);
    }

    private void showUpdateDialog(String url,String message) {
        final AlertDialog dialog = new AlertDialog.Builder(mActivity).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_update);

        final TextView wv1 =  window.findViewById(R.id.diaglog_update_ok);
        final TextView wv2 =  window.findViewById(R.id.diaglog_update_close);// 相册
        final TextView wv3 =  window.findViewById(R.id.diaglog_update_neirong);// 相册
        wv3.setText(message+"\n【需要授权文件读写和安装权限，否则无法更新】");
        wv1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    //读写(高版本)
                    if(!Environment.isExternalStorageManager()){
                        ToastBottomUtils.Setinfo(mActivity,"请授权【读写】权限！");
                        Uri packageUri = Uri.parse("package:" + mActivity.getPackageName());
                        Intent intent4 = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,packageUri);
                        intent4.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mActivity.startActivityForResult(intent4, 1);
                        return;
                    }
                }else{
                    //低版本
                    if(ContextCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(mActivity,"请授权【读写】权限！");
                        String[] permission = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
                        ActivityCompat.requestPermissions(mActivity, permission,1);
                        return;
                    }
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mActivity.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        ToastBottomUtils.Setinfo(mActivity,"请授权【应用安装】权限！");
                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mActivity.getPackageName()));
                        mActivity.startActivityForResult(intent, 1);
                        return;
                    }
                }
                DownloadFileUtil.downloadFile(mActivity,url,url.substring(url.lastIndexOf("/")+1),true);
                Toast.makeText(mActivity,"后台正下载，请稍后...", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
        wv2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }
    
}

